<template>
    <a-modal
      :title="`角色菜单分配 - ${currentRole.name || ''}`"
      :open="visible"
      :width="500"
      :confirm-loading="loading"
      @cancel="visible = false"
      @ok="handleConfirm"
      okText="确定"
      cancelText="取消"
    >
        <a-flex align="center" justify="space-between" style="margin-bottom: 20px">

            <div class="" style="color: #999;">请为角色分配菜单:</div>
            <a-flex align="center" justify="end">
                
                <a-checkbox 
                v-model:checked="checkAllMenus"
                @change="handleCheckAllMenus"
              >
                全选
              </a-checkbox>
              <a-button 
                type="text" 
                @click="checkedKeys = []"
              >
                重置
              </a-button>
            </a-flex>
        </a-flex>
        <a-tree 
        checkable
        :expandedKeys="expandedKeys"
        :checked-keys="checkedKeys"
        @check="checkedKeys = $event"
        :tree-data="menuList"
        v-model:checkedKeys="checkedKeys"
        >
        </a-tree>
    </a-modal>
</template>

<script setup>
    import { ref,computed } from 'vue'
    import { assignMenus } from '@/api/role'
    import { message } from 'ant-design-vue'
    const currentRole = ref({
        name:''
    })
    const loading = ref(false)
    const visible = ref(false)
    const menuList = ref([])
    const checkedKeys = ref([])
    const expandedKeys = computed(() => {
        const keys = []
        menuList.value.forEach(item => {
            if(item.children && item.children.length > 0) {
                keys.push(item._id)
            }
        })
        return keys
    })
    const checkAllMenus = ref(false)
    const handleCheckAllMenus = () => {
        if(checkAllMenus.value) {
            checkedKeys.value = getCheckedKeys()
        } else {
            checkedKeys.value = []
        }
    }
    const getCheckedKeys = () => {
        const keys = []
        keys.push(...getChildKeys(menuList.value))
        return keys
    }
    const getChildKeys = (children) => {
        const keys = []
        children.forEach(child => {
            if(!child.disabled) {
                keys.push(child._id)
                getChildKeys(child.children)
            }
            
        })
        return keys

    }
    const handleConfirm = async () => {
        loading.value = true
        try {
            await assignMenus(currentRole.value.id,checkedKeys.value)
            message.success('分配成功')
            visible.value = false
        } catch (error) {
        } finally {
            loading.value = false
        }
    }

    defineExpose({
        visible,currentRole,menuList,checkedKeys,handleConfirm
    })
</script>